package com.lemon.smartsafety.ui.activity.fire.item.statistics;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.AppBarLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.lemon.android.http.LemonRequestParams;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.BundleKey;
import com.lemon.smartsafety.entity.RefreshViewEntity;
import com.lemon.smartsafety.entity.tab.TabEntity;
import com.lemon.smartsafety.http.HttpBack;
import com.lemon.smartsafety.http.HttpOkBase;
import com.lemon.smartsafety.http.HttpPath;
import com.lemon.smartsafety.result.BaseMode;
import com.lemon.smartsafety.result.fire.FireCompanyBaseScore;
import com.lemon.smartsafety.result.fire.SuperviseCompanyDetail;
import com.lemon.smartsafety.result.fire.SuperviseCompanyResult;
import com.lemon.smartsafetynew.ui.activity.base.NewBaseActivity;
import com.lemon.smartsafety.ui.activity.fire.FirefightingUtil;
import com.lemon.smartsafety.ui.activity.fire.item.inspection.FireInspectionMainActivity;
import com.lemon.smartsafety.ui.activity.fire.item.inspection.FirefightingCompanyAddressActivity;
import com.lemon.smartsafety.ui.adapter.ViewPagerAdapter;
import com.lemon.smartsafety.ui.fragment.fire.FireDeviceFragment;
import com.lemon.smartsafety.ui.fragment.fire.FirePlaceFragment;
import com.lemon.smartsafety.utils.CommonUtil;
import com.lemon.smartsafety.utils.JsonUtils;
import com.lemon.smartsafety.utils.LocationUtil;
import com.lemon.smartsafety.utils.LogUtils;
import com.lemon.smartsafety.utils.app.ToastUtil;
import com.lemon.smartsafety.view.ViewFireTop;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;

public class DeviceStatisticsActivity extends NewBaseActivity {


    @Bind(R.id.main_title)
    TextView mainTitle;
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.app_bar_layout)
    AppBarLayout appBarLayout;
    @Bind(R.id.fireTop)
    ViewFireTop fireTop;
    @Bind(R.id.tl_com)
    CommonTabLayout tlCom;
    @Bind(R.id.viewPager)
    ViewPager viewPager;


    private ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();
    private String[] mTitles = {"按设施分类", "按检查场所"};

    private FragmentPagerAdapter fragmentPagerAdapter;
    private List<Fragment> list;
    private FireDeviceFragment fireDeviceFragment;
    private FirePlaceFragment firePlaceFragment;

    private SuperviseCompanyResult.ResultEntity resultEntity;
    private FireCompanyBaseScore fireCompanyBaseScore;

    private SuperviseCompanyDetail.MyCompanyScoreListEntity myCompanyScoreListEntity;

    private boolean isRefresh = false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void getBundleArgs() {
        if (getIntent().getExtras() != null) {
            resultEntity = (SuperviseCompanyResult.ResultEntity) getIntent().getSerializableExtra(BundleKey.FIRE_COMPANY_BASE_INFO);
            myCompanyScoreListEntity = (SuperviseCompanyDetail.MyCompanyScoreListEntity) getIntent().getSerializableExtra(BundleKey.FIRE_COMPANY_PRO_CODE);

        }
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_device_statistics;
    }

    @Override
    protected void initTitleView() {
        setBarTitle("消防设施完好率");

    }

    @Override
    protected void initView() {


        fireTop.setTitleContent(resultEntity.getCompanyName());
        fireTop.setTitleSubContent("");
        fireTop.setNum1Content("0");
        fireTop.setNum2Content("/0");
        fireTop.setNum1Color(R.color.colorAppRed);
        fireTop.setNum2Color(R.color.colorAppBlue);
        fireTop.setImageCircleShow(true);
        fireTop.setImageCircleBg(R.drawable.shape_circle_red);


        initTab();
    }


    private void initTab() {
        list = new ArrayList<>();
        for (int i = 0; i < mTitles.length; i++) {
            mTabEntities.add(new TabEntity(mTitles[i]));
        }


        for (int i = 0; i < mTitles.length; i++) {
            switch (i) {
                case 0:
                    bundle = new Bundle();
                    bundle.putSerializable(BundleKey.FIRE_COMPANY_BASE_INFO, resultEntity);
                    fireDeviceFragment = new FireDeviceFragment();
                    fireDeviceFragment.setArguments(bundle);
                    list.add(fireDeviceFragment);
                    break;
                case 1:
                    bundle = new Bundle();
                    bundle.putSerializable(BundleKey.FIRE_COMPANY_BASE_INFO, resultEntity);
                    bundle.putString(BundleKey.FIRE_PLACE_TAG, DeviceStatisticsActivity.class.getName());
                    firePlaceFragment = new FirePlaceFragment();
                    firePlaceFragment.setArguments(bundle);
                    list.add(firePlaceFragment);
                    break;
            }
        }

        viewPager.setOffscreenPageLimit(mTitles.length + 1);
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentPagerAdapter = new ViewPagerAdapter(fragmentManager, list);
        viewPager.setAdapter(fragmentPagerAdapter);
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int i) {
                LogUtils.LOGE("Viewpage选择了:" + String.valueOf(i));
                tlCom.setCurrentTab(i);
                if (i == 0) {
                    EventBus.getDefault().post(new RefreshViewEntity(FireDeviceFragment.class.getName()));
                } else {
                    EventBus.getDefault().post(new RefreshViewEntity(FirePlaceFragment.class.getName()));
                }
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });

        tlCom.setTabData(mTabEntities);
        tlCom.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                viewPager.setCurrentItem(position, false);
            }

            @Override
            public void onTabReselect(int position) {
//                if (position == 0) {
//                    mTabs.showMsg(0, new Random().nextInt(100) + 1);
//                }
            }
        });

    }


    @Override
    protected void initHttp() {
        initTopHttp();
    }

    @Override
    protected void initList() {

    }

    @Override
    protected void loadList() {

    }

    @Override
    protected void refreshView() {

    }

    @Override
    protected void callFinish() {
        mActivity.finish();
    }

    public void initTopHttp() {
        LemonRequestParams params = new LemonRequestParams("application_user_bind", "bind_id", "");
        params.put("company_code", resultEntity.getCompanyCode());
        params.put("radio_code", myCompanyScoreListEntity.getTargetCode());


        showLoading("");
        HttpOkBase.httpBasePost(params, HttpPath.getmBase(HttpPath.Get_score), "", new HttpOkBase.HttpInterface() {
            @Override
            public void callBackFunction(boolean httpClient, String result) {

                dismissLoading();
                if (httpClient) {
                    BaseMode baseMode = JsonUtils.fromJson(result, BaseMode.class);
                    if (!CommonUtil.objIsEmpty(baseMode)) {
                        if (HttpBack.httpBackError(baseMode)) {

                            try {
                                fireCompanyBaseScore = mGson.fromJson(mGson.toJson(baseMode.getResult()), FireCompanyBaseScore.class);
                                initTopScore();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        } else {
                            strShowMsg = baseMode.getMsg();
                            handler.sendEmptyMessage(SHOW_MSG);
                        }
                    }
                }
            }
        });

    }

    /**
     * 初始化顶部信息
     */
    private void initTopScore() {
        fireTop.setNum1Color(FirefightingUtil.getScoreTextColor(fireCompanyBaseScore.getStatus()));
        fireTop.setNum2Color(R.color.colorAppBlue);
        fireTop.setNum1Content(fireCompanyBaseScore.getCompanyScore());
        fireTop.setNum2Content("/" + fireCompanyBaseScore.getAvgScore());
        fireTop.setImageCircleBg(FirefightingUtil.getScoreImgCircleColor(fireCompanyBaseScore.getStatus()));
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_inspection, menu);
        return super.onCreateOptionsMenu(menu);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.action_fire_inspection) {
            //点击现场检查
            locationUtil.getLoacation(new LocationUtil.CallBackInterface() {
                @Override
                public void callBackFunction() {
                    LogUtils.LOGE("定位地理位置");
                    signHttp();
                }
            });

        }

        return super.onOptionsItemSelected(item);
    }


    /**
     * 监督签到 是否允许现场检查
     */
    public void signHttp() {
        LemonRequestParams params = new LemonRequestParams("application_user_bind", "bind_id", "");
        params.put("company_code", resultEntity.getCompanyCode());
        params.put("latitude", locationUtil.getmLat());
        params.put("longitude", locationUtil.getmLng());
        params.put("position", locationUtil.getmAddress());

        showLoading("");
        HttpOkBase.httpBasePost(params, HttpPath.getmBase(HttpPath.Sign_in), "", new HttpOkBase.HttpInterface() {
            @Override
            public void callBackFunction(boolean httpClient, String result) {

                dismissLoading();
                if (httpClient) {
                    BaseMode baseMode = JsonUtils.fromJson(result, BaseMode.class);
                    if (!CommonUtil.objIsEmpty(baseMode)) {
                        if (HttpBack.httpBackError(baseMode)) {
                            intent = new Intent(mActivity, FireInspectionMainActivity.class);
                            bundle = new Bundle();
                            bundle.putSerializable(BundleKey.FIRE_COMPANY_BASE_INFO, resultEntity);
                            intent.putExtras(bundle);
                            startActivity(intent);
                        } else {
                            if (baseMode.getCode().equals("2000")) {
                                openCompanyAddress(baseMode);
                            } else {
                                ToastUtil.show(baseMode.getMsg());
                            }
                        }
                    }
                }
            }
        });

    }


    /**
     * 提示用户完善定位信息
     *
     * @param baseMode
     */
    private void openCompanyAddress(BaseMode baseMode) {

        getConfirmDialog(baseMode.getMsg(), R.string.fire_location_sure, R.string.fire_location_cancel, new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                if (which == DialogAction.POSITIVE) {
                    //添加
                    Intent intent = new Intent(mActivity, FirefightingCompanyAddressActivity.class);
                    bundle = new Bundle();
                    bundle.putSerializable(BundleKey.FIRE_COMPANY_BASE_INFO, resultEntity);
                    intent.putExtras(bundle);
                    startActivity(intent);

                }
            }
        }).show();
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (isRefresh) {
            LogUtils.LOGE("onResume通知外页刷新");
/*            EventBus.getDefault().post(new RefreshViewEntity(FireDeviceFragment.class.getName()));
            EventBus.getDefault().post(new RefreshViewEntity(FirePlaceFragment.class.getName()));*/
            EventBus.getDefault().post(new RefreshViewEntity(RefreshViewEntity.REFRESH_TAG));
            isRefresh = false;
        }
    }


    @Override
    protected void onPause() {
        super.onPause();

        isRefresh = true;
    }

}
